-------------------- 第二三章例https://bbs.nga.cn/read.php?tid=25056154 --------------------
local s_find = string.find --local is faster than global
HelloWorld_Text = {}
local channel = "SAY"
local onRollMsg, cancelAuction, subSendChannelMsg, checkPyCmd   --declare

local currentItem
local bids = {}
local bidIdx = 0
local curHighestBid = 0
local prefix = "[叮铃] " --makeColorStr("[叮铃] ", "88ff88")
local advIntervalSec = 9
local pyTollUsage = "用法：startPY <roll点PY让出物品的链接> [限时(秒 <=120 可省略 默认45)]"
local auctionAlreadyRunning = "请等待PY%s结束后重试,距离结束还有TODO秒"
local startingAuction = prefix .. "%s 发起了roll点PY%s,有需求的赶紧roll点抢货,%d秒后本PY结束."
local pyProgress = prefix .. "roll点PY%s,还有%d秒结束."
local noBids = "真遗憾,没人想竞标%s:("
local wonItemFor = "恭喜<%s>勇士以 %d点 赢得了%s."
local pleaseRoll = prefix .. "%s 在PY中%s中一同扔出了最高点%d, 先扔者胜!"
local oldBidDetected = prefix .. "你之前已经掷出%d, 本次roll%d点被驳回(1PY中不可以roll多次)."
local bidPlaced = prefix .. "你掷出了[%d点],竞标成功!"
local pyChannel = "SAY" --GUILD
local DEF_PY_LIMIT_TIME = 15
local pyLimitTime = DEF_PY_LIMIT_TIME -- the time (in seconds) for an auction


sChatMsg = sChatMsg or {}
local eventHandlers = {}
local tasks = {}

--/script PlaySoundFile("Interface/AddOns/GTFO/Sounds/alarmbuzzer.mp3")

function makeUnitLink(nm, clorRGBhexStr)
	return "|Hplayer:".. nm .. "|h|cff" .. clorRGBhexStr .. "[".. nm .."]|r|h"
end
function makeColorStr(str, clorRGBhexStr)
	return "|c00" .. clorRGBhexStr .. str .. "|r"
end
--script DEFAULT_CHAT_FRAME:AddMessage的话链接不起作用， /run也不行  必须在插件中运行才可，而且貌似只能用于本地插件log输出，也就是你通过某channel送出的消息不会起作用，反而啥也不出
--DEFAULT_CHAT_FRAME:AddMessage(makeColorStr("密", "00ff00") .. "我的是：" .. makeUnitLink("西门大棺人 - 血色十字军", "ff0000"))


SLASH_HELLO_WORLD_ADD1 = "/hwadd"
SLASH_HELLO_WORLD_ADD2 = "/helloworldadd"
SlashCmdList["HELLO_WORLD_ADD"] = function(msg)
    --print("hw add enter, msg:" .. msg)
    local id, text = msg:match("(%S+)%s+(.+)")
    --print("id:" .. (id or "NIL"))
    --print("text:" .. (text or "NIL"))

    if not id or not text then
        print("parse msg:[" .. msg .. "] failed.  usage: hwadd <id> <txt>")
        return
    end
    HelloWorld_Text[id:lower()] = text
end

function tableSize(t)
    local leng = 0
    for k, v in pairs(t) do
        leng = leng + 1
    end
    return leng
end

SLASH_HELLO_WORLD_SHOW1 = "/hwshow"
SLASH_HELLO_WORLD_SHOW2 = "/helloworldshow" --just a sample of alias
SlashCmdList["HELLO_WORLD_SHOW"] = function(msg)
    if(not msg) then
        print("uage hwshow <id>")
        return
    end
    
    if("-a" == msg) then --show all 
        print("item count:" .. tableSize(HelloWorld_Text))
        local idx = 0
        for k, v in pairs(HelloWorld_Text) do
            idx = idx + 1
            print("    " .. idx .. ", id:" .. (v or "NIL") .. ", txt:" .. v)
        end
        return
    end

    local text = HelloWorld_Text[msg:lower()]
    if not text then
        print("msg on id[" .. msg:lower() .. "] not found")
        return
    end
    SendChatMessage(text, channel)
end

-------------------- 第四章例https://bbs.nga.cn/read.php?tid=24295645 https://www.cnblogs.com/not2/archive/2004/01/13/12097021.html--------------------
local function showTooltip(self, linkData)
    local linkType = string.split(":", linkData)
    if linkType == "item" or linkType == "spell"
            or linkType == "enchant" or linkType == "quest"
            or linkType == "talent" or linkType == "glyph"
            or linkType == "unit" or linkType == "achievement" then
        GameTooltip:SetOwner(self, "ANCHOR_CURSOR")
        GameTooltip:SetHyperlink(linkData)
        GameTooltip:Show()
    else
        print(linkData)
    end
end
local function hideTooltip()
    GameTooltip:Hide()
end

local function setOrHookHandler(frame, script, func)
    if frame:GetScript(script) then
        frame:HookScript(script, func)
    else
        frame:SetScript(script, func)
    end
end

for i = 1, NUM_CHAT_WINDOWS do
    local frame = getglobal("ChatFrame" .. i)
    if frame then
    --[[
        和TipTac\ttHyperlink.lua功能重复。如果想测试本代码，可以将那边的禁掉，打开本处理，rl下就好
        边貌似是本插件相较于ttHyperlink加载地稍晚，下面代码设置的回调被冲了

        setOrHookHandler(frame, "OnHyperLinkEnter", showTooltip)
        setOrHookHandler(frame, "OnHyperLinkLeave", hideTooltip)
    --]]
    else
        print("frame" .. i .. " not avilable.")
    end
end

local function subAddChatMsgHistoryItem(msg, msgType, sender)
    local t = {}
    t.msg = msg
    t.msgType = msgType
    t.sender = sender
    t.unxTime = time() --date("%Y-%m-%d %H:%M:%S", time())
    --table.insert(sChatMsg, t)
    --print("[" .. sender .. "][" .. msgType .. "]:" .. msg .. "   @" .. t.unxTime)
end

function eventHandlers.CHAT_MSG_WHISPER(msg, sender)
    return subAddChatMsgHistoryItem(msg, "WHISPER", sender)
end
function eventHandlers.CHAT_MSG_WHISPER_INFORM(msg, sender)
    return subAddChatMsgHistoryItem(msg, "WHISPER_INFORM", sender)
end
function eventHandlers.CHAT_MSG_GUILD(msg, sender)
    checkPyCmd(sender, msg, "GUILD")
    return subAddChatMsgHistoryItem(msg, "GUILD", sender)
end
function eventHandlers.CHAT_MSG_SAY(msg, sender)
    checkPyCmd(sender, msg, "SAY")
    return subAddChatMsgHistoryItem(msg, "SAY", sender)
end

function eventHandlers.CHAT_MSG_BN_WHISPER(msg, sender, languageName, channelName, playerName2, specialFlags, zoneChannelID, channelIndex, channelBaseName, unused1, lineID, guid, bnSenderID)
    --print(msg, sender, ...)
--[[  
print("msg=" .. (msg or "NIL"))
print("sender=" .. (sender or "NIL"))
print("languageName=" .. (languageName or "NIL"))
print("channelName=" .. (channelName or "NIL"))
print("playerName2=" .. (playerName2 or "NIL"))
print("specialFlags=" .. (specialFlags or "NIL"))
print("zoneChannelID=" .. (zoneChannelID or "NIL"))
print("channelIndex=" .. (channelIndex or "NIL"))
print("channelBaseName=" .. (channelBaseName or "NIL"))
print("unused1=" .. (unused1 or "NIL"))
print("lineID=" .. (lineID or "NIL"))
print("guid=" .. (guid or "NIL"))
print("bnSenderID=" .. (bnSenderID or "NIL"))
--]]
	if 17 == bnSenderID then --s_find(sender, "尼伯龙")
		print("sender:" .. sender .. ", accountName:" .. C_BattleNet.GetAccountInfoByID(bnSenderID).accountName .. ", battleTag:" .. C_BattleNet.GetAccountInfoByID(bnSenderID).battleTag)
		if s_find(msg, "哥哥") then
			BNSendWhisper(bnSenderID, "今天过的怎么样.嗦了么")
		elseif s_find(msg, "要要") then
			BNSendWhisper(bnSenderID, "二手牛子要不")
		elseif s_find(msg, "我") then
			--BNSendWhisper(bnSenderID, "阿 这")
		else
			--BNSendWhisper(bnSenderID, "啥")
		end
	end
	return subAddChatMsgHistoryItem(msg, "BN_WHISPER", sender)
end
function eventHandlers.CHAT_MSG_BN_WHISPER_INFORM(msg, sender)
    return subAddChatMsgHistoryItem(msg, "BN_WHISPER_INFORM", sender)
end


local function dbgTblKV(t)
    for i, v in pairs(t) do
        print((i or "NIL") .. "=" .. (v or "NIL")) 
    end
end

function eventHandlers.CHAT_MSG_CHANNEL(msg, author, lang, channelNameNo, target, chatFlag, zoneID, channelNo, channelName, chatLineID, senderGUID)
    return subAddChatMsgHistoryItem(msg, "BF_WORLD", author)
    --local ps = {msg, cc, author, lang, channelNameNo, target, chatFlag, zoneID, channelNo, channelName, chatLineID, senderGUID}
    --            1        2        3        4            5        6        7        8            9            10            11
    --dbgTblKV(ps)
    --[[
        比如玩家 棒子姐-血色十字军 在 世界 说 哎哟
        则，收到的参数值如下
            msg:哎哟
            author:棒子姐-血色十字军
            lang:[blank]
            channelNameNo:4.大脚世界频道
            target:棒子姐-血色十字军
            chatFlag:[blank]
            zoneID:27
            channelNo:4
            channelName:大脚世界频道
            chatLineID:0
            senderGUID:3420(常变，即使是同一玩家也有异)
    --]]
    --print(msg, author, lang, channelNameNo, target, chatFlag, zoneID, channelNo, channelName, chatLineID, senderGUID)
end
function eventHandlers.CHAT_MSG_CHANNEL_NOTICE_USER(typ, arg2, arg3, arg4, arg5)
    print("CHAT_MSG_CHANNEL_NOTICE_USER", typ, arg2, arg3, arg4, arg5)
end
function eventHandlers.CHAT_MSG_COMBAT_FACTION_CHANGE(...) print("CHAT_MSG_COMBAT_FACTION_CHANGE", ...) end
function eventHandlers.CHAT_MSG_LOOT(...) print("CHAT_MSG_LOOT ", ...) end
function eventHandlers.CHAT_MSG_PARTY(msg, sender) 
    checkPyCmd(sender, msg, "PARTY")
    --print("CHAT_MSG_PARTY ", msg, sender) 
end
function eventHandlers.CHAT_MSG_PARTY_LEADER(msg, sender) 
    checkPyCmd(sender, msg, "PARTY")
    --print("CHAT_MSG_PARTY_LEADER ", msg, sender)
end


function eventHandlers.CHAT_MSG_INSTANCE_CHAT(...) print("CHAT_MSG_INSTANCE_CHAT ", ...) end
function eventHandlers.CHAT_MSG_INSTANCE_CHAT_LEADER(...) print("CHAT_MSG_INSTANCE_CHAT_LEADER ", ...) end
function eventHandlers.CHAT_MSG_RAID(msg, sender) 
    checkPyCmd(sender, msg, "RAID")
    print("CHAT_MSG_RAID ", msg, sender) 
end
function eventHandlers.CHAT_MSG_RAID_LEADER(msg, sender) 
    checkPyCmd(sender, msg, "RAID")
    print("CHAT_MSG_RAID_LEADER ", msg, sender) 
end
function eventHandlers.CHAT_MSG_RAID_WARNING(...) print("CHAT_MSG_RAID_WARNING ", ...) end
function eventHandlers.CHAT_MSG_SKILL(...) print("CHAT_MSG_SKILL ", ...) end

function eventHandlers.CHAT_MSG_SYSTEM(msg)
    if not currentItem then
        return
    end
    local pYer, rollPointVal, minR, maxR = msg:match("^(.+)掷出(%d+)（(%d+)-(%d+)）")     --50（1-100） thers is no spaceChar!
    
    if (not pYer) or (not rollPointVal) or (not minR) or (not maxR) then
        return
    end
    
    if tonumber(minR) ~= 1 or tonumber(maxR) ~= 100 then
        SendChatMessage("不要耍花招，你这个roll点不合格哈", "WHISPER", nil, pYer)
        return
    end
    onRollMsg(pYer, tonumber(rollPointVal))
end
function eventHandlers.CHAT_MSG_TARGETICONS(...) print("CHAT_MSG_TARGETICONS ", ...) end







function eventHandlers.ZONE_CHANGED_NEW_AREA()
    print("ZONE_CHANGED_NEW_AREA:" .. GetRealZoneText())
    --DEFAULT_CHAT_FRAME:AddMessage("Current Time: " .. time())
end

function eventHandlers.START_LOOT_ROLL(...)
    print("START_LOOT_ROLL")
end
function eventHandlers.UNIT_SPELLCAST_SUCCEEDED(unit, spellName, spellID, arg4, arg5)
    --print("UNIT_SPELLCAST_SUCCEEDED:", unit, spellName, spellID, arg4, arg5)
    --if(unit == "player" or unit == "")

end
function eventHandlers.UNIT_SPELLCAST_SENT(unit, target, spellGUID, spellID)
    --print("UNIT_SPELLCAST_SENT:", unit, target, spellCode, spellID)
    if(unit == "player") then
		
        local name, rank, icon, castTime, minRange, maxRange = GetSpellInfo(spellID)
        --print(icon or "nil1")
		print("I cast[" .. (GetSpellLink(name) or name or "NIL") ..  "], range[" .. (minRange or "NIL") .. ", " .. (maxRange or "NIL") .. "]")
    end
    --unit可以是boss1,target等,所以可以用来监视boss技能?
end
function eventHandlers.COMBAT_LOG_EVENT_UNFILTERED(...)
    --print("COMBAT_LOG_EVENT_UNFILTERED:", ...)
end
function eventHandlers.PARTY_INVITE_REQUEST(inviterName)
    print("PARTY_INVITE_REQUEST:" .. (inviterName or "NIL"))
end



-- return true if want to hide whisper msg
local function isIgnoreWhisperIn(self, event, msg, sender)
    --local name, realm = GetUnitName("player", true)
    if(sender == "西门大棺人-血色十字军") then
        print("hide the msg!!")
        return true
    end
    return false
end

local gXpParams = nil
local function comEventHandler(self, event, ...)
    local e = eventHandlers[event]
    if not e then
        print("no service entry avilable of event:" .. event)
        return
    end
    gXpParams = {...}
    xpcall(function() return e(unpack(gXpParams)) end, function(err) print("ERROR:" .. err) end)
end

local frame1 = CreateFrame("Frame")
frame1:RegisterEvent("CHAT_MSG_WHISPER")
frame1:RegisterEvent("CHAT_MSG_WHISPER_INFORM")
frame1:RegisterEvent("ZONE_CHANGED_NEW_AREA")
frame1:RegisterEvent("CHAT_MSG_GUILD")
frame1:RegisterEvent("START_LOOT_ROLL")
frame1:RegisterEvent("CHAT_MSG_SAY")
frame1:RegisterEvent("UNIT_SPELLCAST_SUCCEEDED")
frame1:RegisterEvent("UNIT_SPELLCAST_SENT")
frame1:RegisterEvent("CHAT_MSG_BN_WHISPER")
frame1:RegisterEvent("CHAT_MSG_BN_WHISPER_INFORM")
frame1:RegisterEvent("CHAT_MSG_CHANNEL")
frame1:RegisterEvent("CHAT_MSG_CHANNEL_NOTICE_USER")
frame1:RegisterEvent("CHAT_MSG_COMBAT_FACTION_CHANGE")
frame1:RegisterEvent("CHAT_MSG_LOOT")
frame1:RegisterEvent("CHAT_MSG_PARTY")
frame1:RegisterEvent("CHAT_MSG_PARTY_LEADER")
frame1:RegisterEvent("CHAT_MSG_INSTANCE_CHAT")
frame1:RegisterEvent("CHAT_MSG_INSTANCE_CHAT_LEADER")
frame1:RegisterEvent("CHAT_MSG_RAID")
frame1:RegisterEvent("CHAT_MSG_RAID_LEADER")
frame1:RegisterEvent("CHAT_MSG_RAID_WARNING")
frame1:RegisterEvent("CHAT_MSG_SKILL")
frame1:RegisterEvent("CHAT_MSG_SYSTEM")
frame1:RegisterEvent("CHAT_MSG_TARGETICONS")
frame1:RegisterEvent("COMBAT_LOG_EVENT_UNFILTERED")
frame1:RegisterEvent("PARTY_INVITE_REQUEST")




frame1:SetScript("OnEvent", comEventHandler)
--ChatFrame_AddMessageEventFilter("CHAT_MSG_WHISPER", isIgnoreWhisperIn) 

function SimpleTimingLib_Schedule(time, func, ...)
    local t = {...}
    t.func = func
    t.time = GetTime() + time
    table.insert(tasks, t)
    print("#tasks:" .. #tasks .. " t.time:" .. t.time)
end
function SimpleTimingLib_Unschedule(func, ...)
    for i = #tasks, 1, -1 do
        local val = tasks[i]
        if val and val.func == func then
            local matches = true
            for i = 1, select("#", ...) do
                if select(i, ...) ~= val[i] then
                    matches = fasle
                    break
                end
            end
            if matches then
                table.remove(tasks, i)
            end
        end
    end
end

local function onUpdate_halfSec()
    for i = #tasks, 1, -1 do
        local val = tasks[i]
        if val and val.time <= GetTime() then
            table.remove(tasks, i)
            val.func(unpack(val))
        end
    end
end
local elpAccum = 0
function onUpdate(self, elapsed)
    elpAccum = elpAccum + elapsed
    if elpAccum >= 0.5 then
        elpAccum = 0
        return onUpdate_halfSec(self, elapsed)
    end
end

function subSendChannelMsg(msg, channel)
    if("SAY" == channel or "GUILD" == channel or "PARTY" == channel or "RAID" == channel) then
        SendChatMessage(msg, channel)
        return
    end
    
    --大脚世界频道 不允许插件自动发话到该频道上,所以这里只是个摆设   CHANNEL本身要求HW(hardware)条件,比如鼠标点击,键盘敲击才能启作用 
    if("BF_WORLD" == channel) then 
        local chnlIdx = GetChannelName("大脚世界频道")
        SendChatMessage(msg, "CHANNEL", nil, chnlIdx)
    end
end


local function aucAdverTimerCb()
	print("aucAdverTimerCb")
    if not currentItem then
        --subSendChannelMsg(pyTollUsage, pyChannel)
    end
    --SimpleTimingLib_Schedule(advIntervalSec, aucAdverTimerCb)
end

--SimpleTimingLib_Schedule(3, print, "Foo5 ", 1, 2, 3)
--SimpleTimingLib_Schedule(5, print, "Foo10 ", 4, 5, 6)
--SimpleTimingLib_Schedule(7, print, "7s passed. ", 7, 8, 9)

--SimpleTimingLib_Schedule(advIntervalSec, aucAdverTimerCb)
--SimpleTimingLib_Unschedule(print, "Foo")
frame1:SetScript("OnUpdate", onUpdate)


local function subGetHighestNameList()
    local highestNameList = bids[1].name .. ", "
    local highestCnt = 1
    for i = 2, #bids do
        if bids[i].bid ~= bids[1].bid then
            break
        else
            highestCnt = highestCnt + 1
            highestNameList = highestNameList .. bids[i].name .. ", "
        end
    end
    highestNameList = highestNameList:sub(0, -3)
    return string.format("共%d人:%s", highestCnt, highestNameList)
end

function startAuction(item, starter, chl)
    if currentItem then
        local msg = auctionAlreadyRunning:format(currentItem)
        if starter then
            SendChatMessage(msg, "WHISPER", nil, starter)
        else
            print(msg)
        end
    else
        currentItem = item
        pyChannel = chl
		--DEFAULT_CHAT_FRAME:AddMessage(startingAuction:format(makeUnitLink(starter, "ff0000"), item, pyLimitTime))
		subSendChannelMsg(startingAuction:format(starter, item, pyLimitTime), pyChannel)

        local remTime = 5
        while(remTime < pyLimitTime) do
            SimpleTimingLib_Schedule(pyLimitTime - remTime, subSendChannelMsg, pyProgress:format(item, remTime), pyChannel)
            remTime = remTime * 3
        end
        SimpleTimingLib_Schedule(pyLimitTime, endPy)

--[[
        table.insert(bids, {bid = 30, name = "dumyName1", bIdx = 9})
        table.insert(bids, {bid = 90, name = "dumyName2", bIdx = 7})
        table.insert(bids, {bid = 58, name = "dumyName3", bIdx = 3})
        table.insert(bids, {bid = 41, name = "dumyName4", bIdx = 12})        
        table.insert(bids, {bid = 96, name = "dumyName5", bIdx = 2})

--]]
    end
end


local function sortBids(v1, v2)
    if v1.bid == v2.bid then
        return v1.bIdx < v2.bIdx
    end
    return v1.bid > v2.bid 
end
local function subReport(wonName, atBidVal)
    local sumReport = prefix .. "PY结束！共" .. #bids .. "人参与了PY.  "
    sumReport = sumReport .. wonItemFor:format(wonName, atBidVal, currentItem)
    if #bids > 3 then
        sumReport = sumReport .. "  前3PY有:"
        for i = 1, 3 do
            sumReport = sumReport .. bids[i].name .. "(" ..  bids[i].bid .. "点) "
        end
    end
    subSendChannelMsg(sumReport, pyChannel)
end


--makeColorStr("密我的是谁", "00ff00") .. "密过你：" .. makeUnitLink("西门大棺人 - 血色十字军", "ff0000"
function endPy()
    local sumReport = prefix .. "PY结束！共" .. #bids .. "人参与PY.  "
    table.sort(bids, sortBids)
    if #bids == 0 then -- case 1:no bid at all
        subSendChannelMsg(sumReport .. noBids:format(currentItem), pyChannel)
    elseif #bids == 1 then -- case 2: one bid; the bidder pays the minmun bid
        subSendChannelMsg(sumReport .. wonItemFor:format(bids[1].name, bids[1].bid, currentItem), pyChannel)
    elseif bids[1].bid ~= bids[2].bid then -- case 3: highest is unique
        subReport(bids[1].name, bids[1].bid)
    else --more then 1 bid and the highest amount is not unique
        subSendChannelMsg(pleaseRoll:format(subGetHighestNameList(), currentItem, bids[1].bid), pyChannel)
        subReport(bids[1].name, bids[1].bid)
  end

  print("set currentItem to nil")
  currentItem = nil
  bidIdx = 0
  curHighestBid = 0
  table.wipe(bids)
end

local function isValidAucArgs(itemLnk, limitSec)
    if (not itemLnk) or (not limitSec) then return false end

    local nLimitSec =  tonumber(limitSec)
    if(not nLimitSec) then return false end
    
    --|cff0070dd|Hitem:138791::::::::50:64::13:::::|h[幻象之书：大地的裂变]|h|r
    
    --all check ok
    return true
end

local function checkHighestBid(bider, curBid)
    if(curBid > curHighestBid) then
        curHighestBid = curBid
        subSendChannelMsg(prefix .. "当前最高出价 ->" .. bider .. "(" .. curHighestBid .. ")", pyChannel)
    end
end

function onRollMsg(sender, bidVal)
    for i, v in ipairs(bids) do -- refresh if that player has already bid
        if sender == v.name then
            SendChatMessage(oldBidDetected:format(v.bid, bidVal), "WHISPER", nil, sender)
            return
        end
    end
    
    bidIdx = bidIdx + 1
    table.insert(bids, {bid = bidVal, name = sender, bIdx = bidIdx})
    SendChatMessage(bidPlaced:format(bidVal), "WHISPER", nil, sender)
end

function checkPyCmd(sender, msg, chnl)
    if currentItem then --PY中
        if(string.sub(msg, 1, 7):lower() == "startpy") then
            print("debug  PY rejected")
            SendChatMessage(auctionAlreadyRunning:format(currentItem), "WHISPER", nil, sender)
            return
        end
        
        if string.sub(msg, 1, 8):lower() == "cancelpy" then
            print("debug  PY cancel")
            cancelAuction(sender)
        end
    end
    
    --非PY中
    if(string.sub(msg, 1, 7):lower() ~= "startpy") then
        return
    end
    
    local itemLnk, limitSec = msg:match("^%w+%s+(.*)%s+(%d+)")
    if not itemLnk or not limitSec then
        itemLnk = msg:match("^%w+%s+([^%s]+)%s*$")
        if itemLnk then
            limitSec = DEF_PY_LIMIT_TIME
        end
    end
    
    if(not isValidAucArgs(itemLnk, limitSec)) then
        SendChatMessage(pyTollUsage, "WHISPER", nil, sender)
        return
    end
    
    local nLimitSec = tonumber(limitSec)
    if(nLimitSec < 1 or nLimitSec > 120) then
        pyLimitTime = DEF_PY_LIMIT_TIME
    else
        pyLimitTime = nLimitSec
    end
    startAuction(itemLnk, sender, chnl)
    return
end

SLASH_SimpleDKP1 = "/simpledkp"
SLASH_SimpleDKP2 = "/sdkp"

local setChannel = "Channel is now \"%s\""
local setTime = "Time is now %s"
local setMinBid = "Lowest bid is now %s"
local currChannel = "Channel is currently set to \"%\""
local currTime = "Time is currently set to %s"

SlashCmdList["SimpleDKP"] = function(msg)
    local cmd, arg = string.split(" ", msg)
    cmd = cmd:lower()
    if cmd == "start" and arg then -- /sdkp start item
        --startAuction(msg:match("^start%s+(.+)"), UnitName("player")) -- extract the item link
    elseif cmd == "stop" then -- /sdkp stop
        cancelAuction()
    elseif cmd == "adv" then
        subSendChannelMsg(pyTollUsage, pyChannel)
    elseif cmd == "channel" then -- /sdkp channel GUILD|SAY
        if arg then
            pyChannel = arg:upper() -- set it to arg
            print(setChannel:format(pyChannel))
        else
            print(currChannel:format(pyChannel))
        end
    end
end

local cancelled = "!!当前roll点PY%s 已被%s取消!!"
function cancelAuction(sender)
    SimpleTimingLib_Unschedule(subSendChannelMsg)
    SimpleTimingLib_Unschedule(endPy)
    subSendChannelMsg(cancelled:format(currentItem, sender or UniName("player")), pyChannel)

    bidIdx = 0
    curHighestBid = 0
    table.wipe(bids)
    currentItem = nil
end

print("[Waoo] load done.")


